package com.work.yshop.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.Product;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.utils.UserSession;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * 商品管理工具类
 * 用于管理商品足迹、收藏、购物车、订单等
 */
public class ProductManager {
    private static final String TAG = "ProductManager";
    private static ProductManager instance;
    
    // SharedPreferences文件名
    private static final String PREF_NAME = "yshop_product_data";
    
    // SharedPreferences键名
    private static final String KEY_HISTORY = "product_history";
    private static final String KEY_FAVORITES = "product_favorites";
    private static final String KEY_CART = "shopping_cart";
    private static final String KEY_ORDERS = "user_orders";
    
    // 最大保存数量
    private static final int MAX_HISTORY_COUNT = 50;
    private static final int MAX_FAVORITES_COUNT = 100;
    
    private Context context;
    private Gson gson;
    
    // 数据缓存
    private List<ProductHistory> historyList;
    private List<Favorite> favoriteList;
    private List<CartItem> cartItems;
    private List<Order> orderList;
    
    private ProductManager(Context context) {
        this.context = context.getApplicationContext();
        this.gson = new Gson();
        loadData();
    }
    
    public static synchronized ProductManager getInstance(Context context) {
        if (instance == null) {
            instance = new ProductManager(context);
        }
        return instance;
    }
    
    /**
     * 从SharedPreferences加载数据
     */
    private void loadData() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        int userId = UserSession.getInstance().getUserId();
        
        // 加载浏览历史
        String historyJson = prefs.getString(KEY_HISTORY + "_" + userId, "");
        Type historyType = new TypeToken<List<ProductHistory>>(){}.getType();
        historyList = gson.fromJson(historyJson, historyType);
        if (historyList == null) {
            historyList = new ArrayList<>();
        }
        
        // 加载收藏
        String favoritesJson = prefs.getString(KEY_FAVORITES + "_" + userId, "");
        Type favoritesType = new TypeToken<List<Favorite>>(){}.getType();
        favoriteList = gson.fromJson(favoritesJson, favoritesType);
        if (favoriteList == null) {
            favoriteList = new ArrayList<>();
        }
        
        // 加载购物车
        String cartJson = prefs.getString(KEY_CART + "_" + userId, "");
        Type cartType = new TypeToken<List<CartItem>>(){}.getType();
        cartItems = gson.fromJson(cartJson, cartType);
        if (cartItems == null) {
            cartItems = new ArrayList<>();
        }
        
        // 加载订单
        String ordersJson = prefs.getString(KEY_ORDERS + "_" + userId, "");
        Type ordersType = new TypeToken<List<Order>>(){}.getType();
        orderList = gson.fromJson(ordersJson, ordersType);
        if (orderList == null) {
            orderList = new ArrayList<>();
        }
    }
    
    /**
     * 保存数据到SharedPreferences
     */
    private void saveData() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        int userId = UserSession.getInstance().getUserId();
        
        editor.putString(KEY_HISTORY + "_" + userId, gson.toJson(historyList));
        editor.putString(KEY_FAVORITES + "_" + userId, gson.toJson(favoriteList));
        editor.putString(KEY_CART + "_" + userId, gson.toJson(cartItems));
        editor.putString(KEY_ORDERS + "_" + userId, gson.toJson(orderList));
        
        editor.apply();
    }
    
    /**
     * 添加商品浏览记录
     */
    public void addHistory(Product product) {
        if (product == null) return;
        
        // 移除已存在的相同商品记录
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).getProductId() == product.getId()) {
                historyList.remove(i);
                break;
            }
        }
        
        // 添加新记录
        ProductHistory history = new ProductHistory(
                product.getId(),
                UserSession.getInstance().getUserId(),
                System.currentTimeMillis()
        );
        history.setProduct(product);
        historyList.add(0, history);
        
        // 控制列表大小
        if (historyList.size() > MAX_HISTORY_COUNT) {
            historyList = historyList.subList(0, MAX_HISTORY_COUNT);
        }
        
        saveData();
    }
    
    /**
     * 获取商品浏览记录列表
     */
    public List<ProductHistory> getHistoryList() {
        return historyList;
    }
    
    /**
     * 清空浏览记录
     */
    public void clearHistory() {
        historyList.clear();
        saveData();
    }
    
    /**
     * 添加收藏
     */
    public void addFavorite(Product product) {
        if (product == null) return;
        
        // 检查是否已收藏
        for (Favorite favorite : favoriteList) {
            if (favorite.getProductId() == product.getId()) {
                return;
            }
        }
        
        // 添加新收藏
        Favorite favorite = new Favorite(
                product.getId(),
                UserSession.getInstance().getUserId(),
                System.currentTimeMillis()
        );
        favorite.setProduct(product);
        favoriteList.add(0, favorite);
        
        // 控制列表大小
        if (favoriteList.size() > MAX_FAVORITES_COUNT) {
            favoriteList = favoriteList.subList(0, MAX_FAVORITES_COUNT);
        }
        
        saveData();
    }
    
    /**
     * 取消收藏
     */
    public void removeFavorite(int productId) {
        for (int i = 0; i < favoriteList.size(); i++) {
            if (favoriteList.get(i).getProductId() == productId) {
                favoriteList.remove(i);
                saveData();
                return;
            }
        }
    }
    
    /**
     * 是否已收藏
     */
    public boolean isFavorite(int productId) {
        for (Favorite favorite : favoriteList) {
            if (favorite.getProductId() == productId) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取收藏列表
     */
    public List<Favorite> getFavoriteList() {
        return favoriteList;
    }
    
    /**
     * 添加商品到购物车
     */
    public void addToCart(Product product, int quantity) {
        if (product == null || quantity <= 0) return;
        
        // 检查购物车是否已有该商品
        for (CartItem item : cartItems) {
            if (item.getProductId() == product.getId()) {
                // 增加数量
                item.setQuantity(item.getQuantity() + quantity);
                saveData();
                return;
            }
        }
        
        // 添加新商品
        CartItem cartItem = new CartItem(
                product.getId(),
                UserSession.getInstance().getUserId(),
                quantity
        );
        cartItem.setProduct(product);
        cartItems.add(cartItem);
        saveData();
    }
    
    /**
     * 更新购物车商品数量
     */
    public void updateCartItemQuantity(int productId, int quantity) {
        if (quantity <= 0) {
            removeCartItem(productId);
            return;
        }
        
        for (CartItem item : cartItems) {
            if (item.getProductId() == productId) {
                item.setQuantity(quantity);
                saveData();
                return;
            }
        }
    }
    
    /**
     * 从购物车移除商品
     */
    public void removeCartItem(int productId) {
        for (int i = 0; i < cartItems.size(); i++) {
            if (cartItems.get(i).getProductId() == productId) {
                cartItems.remove(i);
                saveData();
                return;
            }
        }
    }
    
    /**
     * 获取购物车商品列表
     */
    public List<CartItem> getCartItems() {
        return cartItems;
    }
    
    /**
     * 清空购物车
     */
    public void clearCart() {
        cartItems.clear();
        saveData();
    }
    
    /**
     * 获取购物车商品总数
     */
    public int getCartItemCount() {
        int count = 0;
        for (CartItem item : cartItems) {
            count += item.getQuantity();
        }
        return count;
    }
    
    /**
     * 获取购物车选中商品总价
     */
    public double getCartTotalPrice() {
        double total = 0;
        for (CartItem item : cartItems) {
            if (item.isSelected() && item.getProduct() != null) {
                total += item.getSubtotal();
            }
        }
        return total;
    }
    
    /**
     * 创建订单
     */
    public Order createOrder() {
        // 过滤出选中的购物车项
        List<CartItem> selectedItems = new ArrayList<>();
        for (CartItem item : cartItems) {
            if (item.isSelected() && item.getProduct() != null) {
                selectedItems.add(item);
            }
        }
        
        if (selectedItems.isEmpty()) {
            return null;
        }
        
        // 创建订单
        Order order = new Order();
        
        // 生成订单编号
        String orderNumber = "O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) + 
                String.format("%04d", UserSession.getInstance().getUserId());
        order.setOrderNumber(orderNumber);
        
        // 设置订单信息
        order.setBuyerName(UserSession.getInstance().getUsername());
        order.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
        order.setStatus(Order.STATUS_PENDING);
        
        // 添加订单项
        double totalAmount = 0;
        for (CartItem item : selectedItems) {
            Order.OrderItem orderItem = new Order.OrderItem(
                    item.getProductId(),
                    item.getProduct().getName(),
                    item.getProduct().getPrice(),
                    item.getQuantity(),
                    item.getProduct().getImageUrl()
            );
            order.addItem(orderItem);
            totalAmount += orderItem.getSubtotal();
        }
        order.setTotalAmount(totalAmount);
        
        // 添加到订单列表
        orderList.add(0, order);
        saveData();
        
        // 从购物车中移除已下单的商品
        for (CartItem item : selectedItems) {
            removeCartItem(item.getProductId());
        }
        
        return order;
    }
    
    /**
     * 获取订单列表
     */
    public List<Order> getOrderList() {
        return orderList;
    }
} 